package com.atzongmaotan.reggie.service.impl;

import com.atzongmaotan.reggie.dto.DishDto;
import com.atzongmaotan.reggie.entity.Dish;
import com.atzongmaotan.reggie.entity.DishFlavor;
import com.atzongmaotan.reggie.mapper.DishMapper;
import com.atzongmaotan.reggie.service.DishFlavorService;
import com.atzongmaotan.reggie.service.DishService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName:    DishServiceImpl
 * Package:  com.atzongmaotan.service.impl
 * Description:
 *
 * @Author: interface
 * @Create: 2024/6/14 - 上午5:50
 * @Version: v1.0
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Transactional
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品基本信息到菜品表 dish
        this.save(dishDto);
        Long dishId = dishDto.getId();
        //保存菜品口味数据到菜品口味表 dish_flavor
        List<DishFlavor> dishFlavorList = dishDto.getFlavors();
        dishFlavorList = dishFlavorList.stream().map((item) ->{
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(dishFlavorList);

    }

    @Override
    public DishDto getDishDtoById(Long id) {
        //获取菜品基本信息
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        //获取口味信息,根据dishId
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> flavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
        dishDto.setFlavors(flavorList);
        return dishDto;
    }

    @Transactional
    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //更新Dish 菜品表基本信息
        this.updateById(dishDto);
        //先清理当前菜品对应口味数据,
        Long dishId = dishDto.getId();
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId,dishId);
        dishFlavorService.remove(wrapper);
        //插入当前菜品对应口味数据
        List<DishFlavor> dishFlavorList = dishDto.getFlavors();
        dishFlavorList = dishFlavorList.stream().map((item) ->{
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(dishFlavorList);
    }
}
